import * as React from "react";
import { SocketIOContext } from "./context";
import { io, SocketOptions, Socket, ManagerOptions } from "socket.io-client";
import { ReactNode } from "react";
export interface ISocketIOProviderProps {
  url: string;
  opts?: Partial<ManagerOptions & SocketOptions>;
  children: ReactNode;
}

// const SocketIOProvider = ({ children }: { children: ReactNode })
export const SocketIOProvider: React.FC<ISocketIOProviderProps> = ({
  url,
  opts,
  children,
}) => {
  const socketRef = React.useRef<Socket>();

  if (typeof window === "undefined") {
    return <>{children}</>;
  }

  if (!socketRef.current) {
    console.log('init websocket');
    
    socketRef.current = io(url, opts || {});
  }

  return (
    <SocketIOContext.Provider value={{socket: socketRef.current}}>
      {children}
    </SocketIOContext.Provider>
  );
};
